import { Uri } from "vscode";
import { StopWatch } from "../common/utils/stopWatch";
import { sendTelemetryEvent } from "../telemetry";
import { EventName } from "../telemetry/constants";
import { EQEnvKind } from "./base/info";
import { getEnvPath } from "./base/info/env";
import { EQLocatorQuery, IDiscoveryAPI } from "./base/locator";

export type GetLocatorFunc = () => Promise<IDiscoveryAPI>;

class EQEnvironments implements IDiscoveryAPI {
    private locator!: IDiscoveryAPI;

    constructor(
        // These are factories for the sub-components the full component is composed of:
        private readonly getLocator: GetLocatorFunc,
    ) { }

    public get onRefreshStart() {
        return this.locator.onRefreshStart;
    }
    public get onChanged() {
        return this.locator.onChanged;
    }
    public async triggerRefresh(query?: EQLocatorQuery, trigger?: 'auto' | 'ui') {
        const stopWatch = new StopWatch();
        await this.locator.triggerRefresh(query);
        if (!query) {
            // Intent is to capture time taken for all of discovery to complete, so make sure
            // all interpreters are queried for.
            sendTelemetryEvent(EventName.EQ_INTERPRETER_DISCOVERY, stopWatch.elapsedTime, {
                interpreters: this.getEnvs().length,
                environmentsWithoutEQ: this.getEnvs().filter(
                    (e) => getEnvPath(e.executable.filename, e.location).pathType === 'envFolderPath',
                ).length,
                trigger: trigger ?? 'auto',
            });
        }
    }

    public async activate(): Promise<void> {
        this.locator = await this.getLocator();
    }
    public getEnvs(query?: EQLocatorQuery) {
        return this.locator.getEnvs(query);
    }

}
export async function createEQEnvironments(getLocator: GetLocatorFunc): Promise<IDiscoveryAPI> {
    const api = new EQEnvironments(getLocator);
    await api.activate();
    return api;
}
